package com.blue.base.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.SimpleMessageConverter;

import java.util.Objects;

/**
 * @author liulei
 * @version 1.0
 */
public class CustomJackson2JsonMessageConverter extends Jackson2JsonMessageConverter {


    private SimpleMessageConverter simpleMessageConverter;

    public CustomJackson2JsonMessageConverter() {
        this.simpleMessageConverter = new SimpleMessageConverter();
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        MessageProperties messageProperties = message.getMessageProperties();

        if (Objects.nonNull(messageProperties)) {
            String contentType = messageProperties.getContentType();
            if (Objects.nonNull(contentType) && contentType.contains("json")) {
                return super.fromMessage(message);
            } else if (Objects.nonNull(contentType) && contentType.contains("text")) {
                /*fromMessage-->如果contentType 是text，则将body转为字符串*/
                return simpleMessageConverter.fromMessage(message);
            }
        }
        return super.fromMessage(message);
    }
}
